package com.getpebble.android.jskit.webapps;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.MailTo;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebChromeClient.CustomViewCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.jskit.JsInstalledApplicationInfo;
import com.getpebble.android.jskit.bridge.JsAppContextBridge;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class WebappSupport {
    private WeakReference<WebappRunHost> mBackRef = null;
    private WebSettings mCurrentlyAppliedWebViewSettings = null;
    private boolean mIsWebViewAvailable = false;
    private JsKitAccessor mPrivateJsKitAccess = null;
    private final Lock mPrivateJsKitAccessLock = new ReentrantLock();
    private boolean mTeardownFlag = false;
    private WebView mWebView = null;
    private Lock mWebViewAccessLock = new ReentrantLock();
    private long mWebappProcessId = 0;

    public static class CustomWebViewClient extends WebViewClient {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
        }

        /* JADX WARNING: inconsistent code. */
        /* Code decompiled incorrectly, please refer to instructions dump. */
        public boolean shouldOverrideUrlLoading(android.webkit.WebView r12, java.lang.String r13) {
            /*
            r11 = this;
            r8 = "WebappSupport";
            r9 = new java.lang.StringBuilder;
            r9.<init>();
            r10 = "shouldOverrideUrl: ";
            r9 = r9.append(r10);
            r9 = r9.append(r13);
            r9 = r9.toString();
            com.getpebble.android.common.core.trace.Trace.debug(r8, r9);
            r1 = 0;
            r8 = r12 instanceof com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled;
            if (r8 != 0) goto L_0x001f;
        L_0x001d:
            r8 = 0;
        L_0x001e:
            return r8;
        L_0x001f:
            r3 = 0;
        L_0x0020:
            r13.trim();	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r7 = new java.net.URI;	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r7.<init>(r13);	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r5 = r7.getScheme();	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r8 = "pebblejs";
            r8 = r5.contains(r8);	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            if (r8 == 0) goto L_0x0042;
        L_0x0034:
            r9 = com.getpebble.android.jskit.webapps.JsKit.jsKitAccess();	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r0 = r12;
            r0 = (com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled) r0;	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r8 = r0;
            r1 = r9.handleSpecialUrlForWebViewLoadOverride(r8, r7);	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
        L_0x0040:
            r8 = r1;
            goto L_0x001e;
        L_0x0042:
            r8 = "mailto";
            r8 = r5.contains(r8);	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            if (r8 == 0) goto L_0x0053;
        L_0x004a:
            r0 = r12;
            r0 = (com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled) r0;	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            r8 = r0;
            r1 = r11.handleMailToUrl(r8, r7);	 Catch:{ URISyntaxException -> 0x0055, Exception -> 0x0062 }
            goto L_0x0040;
        L_0x0053:
            r1 = 0;
            goto L_0x0040;
        L_0x0055:
            r6 = move-exception;
            if (r3 != 0) goto L_0x0040;
        L_0x0058:
            r4 = r11.attemptFragmentFix(r13);
            if (r4 != 0) goto L_0x0060;
        L_0x005e:
            r3 = 1;
            goto L_0x0020;
        L_0x0060:
            r13 = r4;
            goto L_0x005e;
        L_0x0062:
            r2 = move-exception;
            goto L_0x0040;
            */
            throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.WebappSupport.CustomWebViewClient.shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String):boolean");
        }

        private boolean handleMailToUrl(WebViewControlled view, URI urlToLoad) {
            try {
                MailTo mailTo = MailTo.parse(urlToLoad.toString());
                if (mailTo == null) {
                    return false;
                }
                try {
                    Intent showMailToActivity = new Intent("android.intent.action.SEND");
                    showMailToActivity.putExtra("android.intent.extra.EMAIL", new String[]{mailTo.getTo()});
                    showMailToActivity.putExtra("android.intent.extra.CC", mailTo.getCc());
                    showMailToActivity.putExtra("android.intent.extra.SUBJECT", mailTo.getSubject());
                    showMailToActivity.putExtra("android.intent.extra.TEXT", mailTo.getBody());
                    showMailToActivity.setType("message/rfc822");
                    showMailToActivity.setFlags(268435456);
                    view.getContext().startActivity(showMailToActivity);
                    view.reload();
                    return true;
                } catch (Exception e) {
                    Trace.warning("WebappSupport", "unable to start mail activity from request", e);
                    return false;
                }
            } catch (ParseException e2) {
                Trace.info("WebappSupport", "viewed page has an incorrect mailto link", e2);
                return false;
            } catch (Exception e3) {
                Trace.warning("WebappSupport", "unexpected problem parsing mailto link", e3);
                return false;
            }
        }

        private String attemptFragmentFix(String url) {
            int indexOfFragmentStartMark = url.indexOf("#");
            if (indexOfFragmentStartMark == -1 || indexOfFragmentStartMark == url.length() - 1) {
                return null;
            }
            String basePart = url.substring(0, indexOfFragmentStartMark);
            try {
                return basePart + "#" + URLEncoder.encode(url.substring(indexOfFragmentStartMark + 1), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }

        public void onPageFinished(WebView view, String url) {
            Trace.debug("WebappSupport", "onPageFinished: " + url);
            if (view instanceof WebViewControlled) {
                JsKit.jsKitAccess().webViewOnPageFinished((WebViewControlled) view, url);
            }
        }

        private InputStream inputStreamForAndroidResource(String url) {
            String ANDROID_ASSET = "file:///android_asset/";
            if (url.startsWith("file:///android_asset/")) {
                try {
                    return JsAppContextBridge.getInstance().getAppContext().getAssets().open(Uri.parse(url.replaceFirst("file:///android_asset/", "")).getPath(), 2);
                } catch (IOException e) {
                }
            }
            return null;
        }

        /* JADX WARNING: inconsistent code. */
        /* Code decompiled incorrectly, please refer to instructions dump. */
        public android.webkit.WebResourceResponse shouldInterceptRequest(android.webkit.WebView r16, java.lang.String r17) {
            /*
            r15 = this;
            r12 = "WebappSupport";
            r13 = new java.lang.StringBuilder;
            r13.<init>();
            r14 = "shouldInterceptRequest url = ";
            r13 = r13.append(r14);
            r0 = r17;
            r13 = r13.append(r0);
            r13 = r13.toString();
            com.getpebble.android.common.core.trace.Trace.verbose(r12, r13);
            r0 = r16;
            r12 = r0 instanceof com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled;
            if (r12 != 0) goto L_0x0022;
        L_0x0020:
            r5 = 0;
        L_0x0021:
            return r5;
        L_0x0022:
            r12 = android.os.Build.VERSION.SDK_INT;
            r13 = 15;
            if (r12 > r13) goto L_0x0035;
        L_0x0028:
            r1 = 1;
        L_0x0029:
            r2 = r16;
            r2 = (com.getpebble.android.jskit.webapps.WebappSupport.WebViewControlled) r2;
            r6 = r2.getOwnerClientId();
            if (r6 != 0) goto L_0x0037;
        L_0x0033:
            r5 = 0;
            goto L_0x0021;
        L_0x0035:
            r1 = 0;
            goto L_0x0029;
        L_0x0037:
            r4 = 0;
        L_0x0038:
            r17.trim();	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            r11 = new java.net.URI;	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            r0 = r17;
            r11.<init>(r0);	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            r8 = r11.getScheme();	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            r12 = "pebblejsresource";
            r12 = r8.contains(r12);	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            if (r12 != 0) goto L_0x0056;
        L_0x004e:
            r12 = "file";
            r12 = r8.equalsIgnoreCase(r12);	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            if (r12 == 0) goto L_0x006c;
        L_0x0056:
            r12 = com.getpebble.android.jskit.webapps.JsKit.jsKitAccess();	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            r0 = r17;
            r5 = r12.handleLocalResourceLoadByWebapp(r6, r11, r0);	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            r12 = "file";
            r12 = r8.equalsIgnoreCase(r12);	 Catch:{ URISyntaxException -> 0x0084, Exception -> 0x0094 }
            if (r12 == 0) goto L_0x0021;
        L_0x0068:
            if (r1 == 0) goto L_0x0021;
        L_0x006a:
            if (r5 != 0) goto L_0x0021;
        L_0x006c:
            r12 = android.os.Build.VERSION.SDK_INT;
            r13 = 15;
            if (r12 > r13) goto L_0x0096;
        L_0x0072:
            r0 = r17;
            r10 = r15.inputStreamForAndroidResource(r0);
            if (r10 == 0) goto L_0x0096;
        L_0x007a:
            r5 = new android.webkit.WebResourceResponse;
            r12 = "text/html";
            r13 = "UTF-8";
            r5.<init>(r12, r13, r10);
            goto L_0x0021;
        L_0x0084:
            r9 = move-exception;
            if (r4 != 0) goto L_0x006c;
        L_0x0087:
            r0 = r17;
            r7 = r15.attemptFragmentFix(r0);
            if (r7 != 0) goto L_0x0091;
        L_0x008f:
            r4 = 1;
            goto L_0x0038;
        L_0x0091:
            r17 = r7;
            goto L_0x008f;
        L_0x0094:
            r3 = move-exception;
            goto L_0x006c;
        L_0x0096:
            r5 = super.shouldInterceptRequest(r16, r17);
            goto L_0x0021;
            */
            throw new UnsupportedOperationException("Method not decompiled: com.getpebble.android.jskit.webapps.WebappSupport.CustomWebViewClient.shouldInterceptRequest(android.webkit.WebView, java.lang.String):android.webkit.WebResourceResponse");
        }
    }

    public static class IDRecycler {
        protected long gen = 1;
        protected TreeSet<Long> invalidValues = new TreeSet();
        protected TreeSet<Long> values = new TreeSet();

        public IDRecycler() {
            this.invalidValues.add(Long.valueOf(0));
        }

        public synchronized long issue() {
            long cv;
            Long v = (Long) this.values.pollFirst();
            if (v == null) {
                cv = this.gen;
                this.gen = cv + 1;
                while (this.invalidValues.contains(Long.valueOf(cv))) {
                    cv = this.gen;
                    this.gen = cv + 1;
                }
            } else {
                cv = v.longValue();
            }
            return cv;
        }
    }

    private static class IDRecyclerRef {
        public static IDRecycler INST = new IDRecycler();
    }

    public static class QueuedLoadUrlContainer {
        public final LoadTypeE LoadType;
        public final String UrlString;

        public enum LoadTypeE {
            _INVALID_,
            WithBootstrapScripts,
            WithoutBootstrapScripts
        }

        public QueuedLoadUrlContainer() {
            this.LoadType = LoadTypeE._INVALID_;
            this.UrlString = "";
        }

        public QueuedLoadUrlContainer(String urlString, LoadTypeE type) {
            if (urlString == null) {
                type = LoadTypeE._INVALID_;
            } else if (type == null) {
                type = LoadTypeE._INVALID_;
            }
            this.LoadType = type;
            if (urlString == null) {
                urlString = "";
            }
            this.UrlString = urlString;
        }
    }

    public static class WebViewControlled extends WebView {
        protected final UUID mOwnerClientId;
        protected boolean mZombie;

        public WebViewControlled(UUID clientId, Context context) {
            super(context);
            if (clientId == null) {
                clientId = new UUID(0, 0);
            }
            this.mOwnerClientId = clientId;
            this.mZombie = false;
        }

        public UUID getOwnerClientId() {
            return this.mOwnerClientId;
        }

        public void gatedInvalidateRunOnUiThread() {
            Context ref = getContext();
            if (ref instanceof Activity) {
                ((Activity) ref).runOnUiThread(new Runnable() {
                    public void run() {
                        WebViewControlled.this.invalidate();
                    }
                });
            }
        }

        public boolean onTouchEvent(MotionEvent event) {
            if (this.mZombie) {
                return false;
            }
            if (event.getAction() == 0) {
                scrollBy(0, 1);
                scrollBy(0, -1);
            }
            boolean rv = super.onTouchEvent(event);
            gatedInvalidateRunOnUiThread();
            return rv;
        }

        public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
            if (!this.mZombie) {
                additionalHttpHeaders.put("Pragma", "no-cache");
                additionalHttpHeaders.put("Cache-Control", "no-cache");
                super.loadUrl(url, additionalHttpHeaders);
            }
        }

        public void loadUrl(final String url) {
            if (url == null || url.length() < 1) {
                Trace.debug("WebappSupport", "Parameter 'url' is null!");
            } else if (!this.mZombie) {
                final Map<String, String> noCacheHeaders = new HashMap(2);
                noCacheHeaders.put("Pragma", "no-cache");
                noCacheHeaders.put("Cache-Control", "no-cache");
                try {
                    if (Looper.myLooper() == null) {
                        Trace.error("WebappSupport", "loadURL: thread lost its looper.  assuming main thread...");
                        Handler h = new Handler(JsAppContextBridge.getInstance().getAppContext().getMainLooper());
                        if (h == null) {
                            Trace.error("WebappSupport", "loadURL: can't get mainLooper.  bailing.");
                            return;
                        } else {
                            h.post(new Runnable() {
                                public void run() {
                                    super.loadUrl(url, noCacheHeaders);
                                }
                            });
                            return;
                        }
                    }
                    super.loadUrl(url, noCacheHeaders);
                } catch (Throwable npe) {
                    npe.printStackTrace();
                    Trace.debug("WebappSupport", npe);
                }
            }
        }

        public void destroy() {
            super.destroy();
            this.mZombie = true;
        }
    }

    public static long issueId() {
        return IDRecyclerRef.INST.issue();
    }

    public static WebappSupport makeMeMyWebappSupportObject(WebappRunHost selfRef) {
        if (selfRef == null) {
            return null;
        }
        return new WebappSupport(selfRef);
    }

    protected WebappSupport() {
    }

    protected WebappSupport(WebappRunHost forBackRefToHost) {
        this.mBackRef = new WeakReference(forBackRefToHost);
        this.mWebappProcessId = issueId();
    }

    protected WebView recreateWebViewWithAutocontextDetection() {
        if (this.mBackRef == null) {
            return recreateWebView(null);
        }
        WebappRunHost backRefTmp = (WebappRunHost) this.mBackRef.get();
        if (backRefTmp == null) {
            return recreateWebView(null);
        }
        if (backRefTmp instanceof WebappGenericBaseFragment) {
            return recreateWebView((Activity) ((WebappGenericBaseFragment) backRefTmp).getBackingContext());
        }
        return recreateWebView(null);
    }

    protected WebView recreateWebView() {
        return recreateWebViewWithAutocontextDetection();
    }

    @SuppressLint({"NewApi"})
    protected WebView recreateWebView(Context useThisBackingContextForWebView) {
        if (((WebappRunHost) this.mBackRef.get()) == null) {
            return null;
        }
        this.mWebViewAccessLock.lock();
        if (this.mWebView != null) {
            safeDestroyMemberWebView();
            this.mWebView = null;
            this.mIsWebViewAvailable = false;
        }
        UUID clientId = null;
        try {
            clientId = ((WebappRunHost) this.mBackRef.get()).clientUuid();
        } catch (Exception e) {
        }
        if (useThisBackingContextForWebView == null) {
            useThisBackingContextForWebView = JsAppContextBridge.getInstance().getAppContext();
        }
        this.mWebView = new WebViewControlled(clientId, useThisBackingContextForWebView);
        this.mCurrentlyAppliedWebViewSettings = this.mWebView.getSettings();
        if (VERSION.SDK_INT <= 18) {
            try {
                this.mCurrentlyAppliedWebViewSettings.setSavePassword(false);
            } catch (Exception e2) {
                Trace.warning("WebappSupport", "This platform " + VERSION.SDK_INT + " SHOULD support setSavePassword" + "(false) but it doesn't! The app will likely crash when a webpage invokes a save passw dialog!");
            }
        }
        this.mCurrentlyAppliedWebViewSettings.setJavaScriptEnabled(true);
        this.mCurrentlyAppliedWebViewSettings.setAllowFileAccess(true);
        if (VERSION.SDK_INT >= 16) {
            this.mCurrentlyAppliedWebViewSettings.setAllowUniversalAccessFromFileURLs(true);
            this.mCurrentlyAppliedWebViewSettings.setAllowFileAccessFromFileURLs(true);
        }
        this.mCurrentlyAppliedWebViewSettings.setAllowContentAccess(true);
        File webAppStorageDir = JsAppContextBridge.getInstance().getAppContext().getDir("webapps_stor", 4);
        if (!webAppStorageDir.mkdirs()) {
            Trace.warning("WebappSupport", "mkdirs " + webAppStorageDir.getAbsolutePath() + " returned FALSE");
        }
        this.mCurrentlyAppliedWebViewSettings.setDatabasePath(webAppStorageDir.getAbsolutePath());
        this.mCurrentlyAppliedWebViewSettings.setDatabaseEnabled(true);
        this.mCurrentlyAppliedWebViewSettings.setDomStorageEnabled(true);
        File webCacheDir = JsAppContextBridge.getInstance().getAppContext().getCacheDir();
        if (!webCacheDir.mkdirs()) {
            Trace.warning("WebappSupport", "mkdirs " + webCacheDir.getAbsolutePath() + " returned FALSE");
        }
        this.mCurrentlyAppliedWebViewSettings.setAppCachePath(webCacheDir.getAbsolutePath());
        this.mCurrentlyAppliedWebViewSettings.setAppCacheEnabled(true);
        this.mCurrentlyAppliedWebViewSettings.setCacheMode(2);
        this.mWebView.clearCache(true);
        this.mWebView.addJavascriptInterface(getPrivateJsKitAccess(), "Pebble");
        this.mWebView.setWebViewClient(new CustomWebViewClient());
        this.mWebView.setWebChromeClient(new WebChromeClient() {
            public void onGeolocationPermissionsShowPrompt(String origin, Callback callback) {
                Trace.verbose("WebappSupport", "onGeolocationPermissionsShowPrompt origin = " + origin);
                callback.invoke(origin, true, false);
            }

            public boolean onConsoleMessage(ConsoleMessage cm) {
                String source = cm.sourceId();
                String clientUUIDString = ((WebappRunHost) WebappSupport.this.mBackRef.get()).clientUuidAsString();
                if (clientUUIDString != null) {
                    UUID appUuid = JsKit.jsKitAccess().currentActiveAppUuid(clientUUIDString);
                    if (appUuid != null) {
                        JsInstalledApplicationInfo appInfo = JsKit.installedWebappsInfoForUuid(appUuid);
                        if (appInfo != null) {
                            if (appInfo.getShortName() != null) {
                                source = appInfo.getShortName();
                            } else if (appInfo.getLongName() != null) {
                                source = appInfo.getLongName();
                            }
                        }
                    }
                }
                Trace.debug("WebappSupport", String.format("%s:%d %s", new Object[]{source, Integer.valueOf(cm.lineNumber()), cm.message()}));
                String installPath = JsKit.webAppInstallDirectoryAbsPath();
                if (installPath == null) {
                    installPath = "";
                }
                int installPathIndex = -1;
                try {
                    installPathIndex = cm.sourceId().indexOf(installPath);
                } catch (Exception e) {
                }
                if (installPathIndex < 0) {
                    return true;
                }
                String relativeFilename = cm.sourceId().substring((installPath.length() + installPathIndex) + 1);
                logRepeater(String.format("%s:%d %s", new Object[]{relativeFilename, Integer.valueOf(cm.lineNumber()), cm.message()}));
                return true;
            }

            protected void logRepeater(String formedMessage) {
                UUID clientUUID = null;
                try {
                    clientUUID = ((WebappRunHost) WebappSupport.this.mBackRef.get()).clientUuid();
                } catch (Exception e) {
                }
                JsKit.loggerForWebapps(clientUUID, formedMessage);
            }

            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                return false;
            }

            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return false;
            }

            public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
                return false;
            }

            public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
                return false;
            }

            public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
                return false;
            }

            public void onShowCustomView(View view, CustomViewCallback callback) {
                System.out.checkError();
            }
        });
        this.mIsWebViewAvailable = true;
        WebView rv = this.mWebView;
        this.mWebViewAccessLock.unlock();
        return rv;
    }

    protected WebappRunHost getWebappHostRefIfStillValid() {
        if (this.mBackRef != null) {
            return (WebappRunHost) this.mBackRef.get();
        }
        return null;
    }

    public JsKitAccessor getPrivateJsKitAccess() {
        this.mPrivateJsKitAccessLock.lock();
        if (this.mPrivateJsKitAccess == null) {
            WebappRunHost host = getWebappHostRefIfStillValid();
            if (host != null) {
                this.mPrivateJsKitAccess = new JsKitAccessor(host);
            } else {
                Trace.error("WebappSupport", "getPrivateJsKitAccess: This shouldn't happen");
            }
        }
        this.mPrivateJsKitAccessLock.unlock();
        return this.mPrivateJsKitAccess;
    }

    public WebView getWebView() {
        this.mWebViewAccessLock.lock();
        if (this.mWebView == null) {
            Trace.debug("WebappSupport", "getWebView: mWebView = null");
            this.mIsWebViewAvailable = false;
        }
        WebView rv = this.mWebView;
        this.mWebViewAccessLock.unlock();
        return rv;
    }

    public void onCreateOnOwner(Bundle savedInstanceState) {
        this.mWebViewAccessLock.lock();
        if (this.mWebView == null) {
            Trace.debug("WebappSupport", "onCreateOnOwner: mWebView = null; re-creating");
            this.mWebView = recreateWebView();
        }
        this.mIsWebViewAvailable = this.mWebView != null;
        this.mWebViewAccessLock.unlock();
    }

    public View onCreateViewOnOwner(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mWebViewAccessLock.lock();
        if (this.mWebView == null) {
            this.mWebView = recreateWebView();
        } else {
            safeRemoveFromViewTreeMemberWebView();
        }
        this.mIsWebViewAvailable = this.mWebView != null;
        WebView rv = getWebView();
        this.mWebViewAccessLock.unlock();
        return rv;
    }

    public void onPauseOnOwner() {
        this.mWebViewAccessLock.lock();
        if (this.mWebView != null) {
            this.mWebView.onPause();
        }
        this.mWebViewAccessLock.unlock();
    }

    public void onResumeOnOwner() {
        this.mWebViewAccessLock.lock();
        if (this.mWebView != null) {
            this.mWebView.onResume();
        }
        this.mWebViewAccessLock.unlock();
    }

    public void onDestroyViewOnOwner() {
        this.mWebViewAccessLock.lock();
        this.mIsWebViewAvailable = false;
        safeRemoveFromViewTreeMemberWebView();
        this.mWebViewAccessLock.unlock();
    }

    public void flagForSubsequentTeardownOnDestroy() {
        this.mWebViewAccessLock.lock();
        this.mTeardownFlag = true;
        this.mWebViewAccessLock.unlock();
    }

    public boolean onDestroyOnOwner() {
        this.mWebViewAccessLock.lock();
        if (this.mTeardownFlag) {
            safeDestroyMemberWebView();
            this.mWebView = null;
        }
        this.mIsWebViewAvailable = false;
        boolean rv = this.mTeardownFlag;
        this.mWebViewAccessLock.unlock();
        return rv;
    }

    protected void safeDestroyMemberWebView() {
        safeRemoveFromViewTreeMemberWebView();
        this.mWebView.loadUrl("about:blank");
        this.mWebView.stopLoading();
        this.mWebView.destroy();
    }

    protected void safeRemoveFromViewTreeMemberWebView() {
        ViewGroup webViewParent = (ViewGroup) this.mWebView.getParent();
        if (webViewParent != null) {
            webViewParent.removeView(this.mWebView);
        }
    }

    public long getWebappProcessId() {
        return this.mWebappProcessId;
    }

    public static InputStream inputStreamForResource(String urlStringForResource) {
        if (urlStringForResource == null) {
            return null;
        }
        try {
            URI fileUri = new URL(urlStringForResource).toURI();
            if (fileUri.getPath().startsWith("/android_asset/")) {
                return inputStreamForAssetManagerResource(fileUri);
            }
            return new FileInputStream(new File(fileUri));
        } catch (Throwable e) {
            Trace.debug("WebappSupport", e);
            return null;
        }
    }

    protected static InputStream inputStreamForAssetManagerResource(URI uriForResource) {
        InputStream inputStream = null;
        AssetManager am = JsAppContextBridge.getInstance().getAppContext().getAssets();
        if (am == null) {
            PebbleWebappBaseActivity.LogSimpleError("%s::%s : no AssetManager was returned by the system (?!!)", NoUiWebappBase.class.getSimpleName(), "inputStreamForAssetManagerResource");
        } else {
            String attemptedPath = "";
            try {
                String fullPath = uriForResource.getPath();
                if (fullPath.startsWith("/android_asset/")) {
                    inputStream = am.open(fullPath.substring("/android_asset/".length()));
                }
            } catch (Exception e) {
            }
        }
        return inputStream;
    }
}
